package lzh.com.customeroilactivity.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import lzh.com.customeroilactivity.Bean.Address;
import lzh.com.customeroilactivity.NewBaseActivity;
import lzh.com.customeroilactivity.R;
import lzh.com.customeroilactivity.widget.OnWheelChangedListener;
import lzh.com.customeroilactivity.widget.WheelView;
import lzh.com.customeroilactivity.widget.adapters.ArrayWheelAdapter;

public class AddAdressActivity extends NewBaseActivity implements View.OnClickListener, OnWheelChangedListener {
    private TextView title;
    private ImageButton back;
    private EditText name;
    private EditText iphone;
    private RelativeLayout layout;
    private LinearLayout list;
    private EditText address;
    private TextView tvIphone;
    private TextView tvName;
    private TextView tvAddress;
    private TextView go;

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView no;
    private TextView yes;

    private SharedPreferences sharedPreferences;
    private int dataNumber = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_adress);
        Bmob.initialize(this, "5e509d9bd6152b90a5e72d4cade54c5f");
        sharedPreferences = this.getSharedPreferences("userData",MODE_PRIVATE);
        init();
    }

    private void init(){
        title = (TextView)findViewById(R.id.title_bar);
        back = (ImageButton)findViewById(R.id.top_left_btn);
        name = (EditText)findViewById(R.id.name);
        iphone = (EditText)findViewById(R.id.iphone);
        layout = (RelativeLayout) findViewById(R.id.layout2);
        list = (LinearLayout)findViewById(R.id.list);
        address = (EditText)findViewById(R.id.address);
        tvIphone = (TextView)findViewById(R.id.tv_iphone);
        tvName = (TextView)findViewById(R.id.tv_name);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        go = (TextView)findViewById(R.id.go);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        title.setText("新增地址");
        tvIphone.setText("电话："+"\u3000\u3000");
        tvName.setText("收货人："+"\u3000");
        list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(AddAdressActivity.this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
                    //如果不同意，就去请求权限   参数1：上下文，2：权限，3：请求码
                    ActivityCompat.requestPermissions(AddAdressActivity.this,new String []{Manifest.permission.READ_CONTACTS},1);
                }else {

                    Uri uri = Uri.parse("content://contacts/people");
                    Intent intent = new Intent(Intent.ACTION_PICK, uri);
                    startActivityForResult(intent, 0);
                }
            }
        });

        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View view1 = LayoutInflater.from(AddAdressActivity.this).inflate(R.layout.show_address,null);
                mViewProvince = (WheelView) view1.findViewById(R.id.id_province);
                mViewCity = (WheelView) view1.findViewById(R.id.id_city);
                mViewDistrict = (WheelView) view1.findViewById(R.id.id_district);
                no = (TextView)view1.findViewById(R.id.no);
                yes = (TextView)view1.findViewById(R.id.yes);

                final AlertDialog dialog = new AlertDialog.Builder(AddAdressActivity.this,R.style.DialogStyle)
                        .setView(view1)
                        .create();
                dialog.show();
                setUpListener();
                setUpData();

                Window window = dialog.getWindow();
                window.setGravity(Gravity.BOTTOM);
                window.setWindowAnimations(R.style.popupAnimation);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);

                WindowManager m = AddAdressActivity.this.getWindowManager();
                Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
                WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值   
                p.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的1，根据实际情况调整
                window.setAttributes(p);

                no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });

                yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        tvAddress.setText(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
                        dialog.dismiss();
                    }
                });
            }
        });

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (name.getText().toString().length()==0){
                    Toast.makeText(AddAdressActivity.this, "请填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (iphone.getText().toString().length()==0){
                    Toast.makeText(AddAdressActivity.this, "请填写手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (tvAddress.getText().toString().length()==0){
                    Toast.makeText(AddAdressActivity.this, "请填写收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (address.getText().toString().length()==0){
                    Toast.makeText(AddAdressActivity.this, "请填写详细地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                find();


            }
        });
    }

    private void find(){

        Address add = new Address();
        add.setUserId(sharedPreferences.getInt("userId",0));
        add.setName(name.getText().toString());
        add.setIphone(iphone.getText().toString());
        add.setAddress(tvAddress.getText().toString());
        add.setDetailedAddress(address.getText().toString());
        add.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Toast.makeText(AddAdressActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    ReceivingAddressActivity.receivingAddressActivity.find();
                    finish();
                }else {
                    Toast.makeText(AddAdressActivity.this, "保存失败，请联系管理员，qq:389617853", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(AddAdressActivity.this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AddAdressActivity.this, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(6);
        mViewCity.setVisibleItems(6);
        mViewDistrict.setVisibleItems(6);
        updateCities();
        updateAreas();
    }


    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    private String[] getPhoneContacts(Uri uri){
        String[] contact=new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor=cr.query(uri,null,null,null,null);
        if(cursor!=null)
        {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0]=cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if(phone != null){
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        }
        else
        {
            return null;
        }
        return contact;
    }

    /*
     * 跳转联系人列表的回调函数
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 0:
                if(data==null)
                {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri=data.getData();
                String[] contacts=getPhoneContacts(uri);
                name.setText(contacts[0]);
                iphone.setText(contacts[1]);
                name.setSelection(name.length());
                iphone.setSelection(iphone.length());
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //判断请求码
        switch (requestCode){
            case 1:
                //如果同意
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){

                    Uri uri = Uri.parse("content://contacts/people");
                    Intent intent = new Intent(Intent.ACTION_PICK, uri);
                    startActivityForResult(intent, 0);
                }else{
                    Toast.makeText(this,"请同意查看通讯录的权限",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    @Override
    public void onClick(View v) {

    }

}
